package com.cubeofnine.sugar.activity.import_contact;

import java.util.Iterator;
import java.util.List;

import com.cubeofnine.android.api.ContactAPI;
import com.cubeofnine.sugar.R;
import com.cubeofnine.sugar.service.element.Contact;

import android.content.ContentResolver;
import android.content.Context;
import android.os.Handler;
import android.util.Log;

public class SyncDownContactsListThread extends Thread {
	private Context context;
	private List<Contact> contacts;
	private Handler handler = new Handler();

	public SyncDownContactsListThread(Context context, List<Contact> contacts) {
		super();
		this.context = context;
		this.contacts = contacts;
	}

	public String getClassName() {
		return SyncDownContactsListThread.class.getName();
	}

	@Override
	public void run() {
		Log.i(getClassName(), "run() : Start");

		int totalCount = 0;
		int insertCount = 0;
		String errorMessage = "";
		try {
			ContentResolver cr = context.getContentResolver();
			ContactAPI api = new ContactAPI();
			api.setCr(cr);

			totalCount = contacts.size();

			String groupName = "SugarCRM Group";

			long groupId = api.getGroupIdByName(groupName);
			Log.d(getClassName(), "Old : groupId = " + groupId);

			if (groupId == -1) {
				groupId = api.createNewGroup(groupName);
			}

			Log.d(getClassName(), "New : groupId = " + groupId);

			long contactId = -1;

			String displayName = "";
			Contact contact = null;
			Iterator<Contact> contactIter = contacts.iterator();
			while (contactIter.hasNext()) {
				contact = contactIter.next();

				contactId = -1;
				displayName = "";

				if (contact.getFirst_name() != null
						&& !contact.getFirst_name().isEmpty()) {
					displayName = contact.getFirst_name();
				}

				if (contact.getLast_name() != null
						&& !contact.getLast_name().isEmpty()) {
					displayName += " " + contact.getLast_name();
				}

				displayName = displayName.trim();

				contactId = api.createNewContact(displayName,
						contact.getCompany_name(), contact.getJob_title(),
						contact.getPhones(), contact.getEmails(),
						contact.getAddresses());

				Log.d(getClassName(), "contactId = " + contactId);

				if (groupId != -1 && contactId != -1) {
					Log.d(getClassName(), "setGroup = "
							+ api.setContactMembership(contactId, groupId)
									.toString());
				}

				if (contactId != -1) {
					insertCount++;
				}
			}
		} catch (Exception e) {
			Log.e(getClassName(), "Connection Error", e);
			errorMessage = context.getString(R.string.msg_application_error);
		} finally {
			Log.d(getClassName(), "Finally");
			handler.post(new SyncDownContactsListRunnable(context, totalCount,
					insertCount, errorMessage));
		}

		Log.i(getClassName(), "run() : End");
	}
}
